package com.dogkr.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.dogkr.server.entity.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 拦截器
 * @author Wang
 *
 */


public class LoginManagerInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	public static final String TIMEOUT = "timeout";
	
	public void destroy() {
		
	}

	public void init() {
		
	}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		//获取request
		ActionContext context = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse)context.get(ServletActionContext.HTTP_RESPONSE);
		//获取session
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constants.LOGIN_USER_KEY);
		if (user != null && user.getStatus() != null && User.STATUS_MANAGER == user.getStatus()) {
			return invocation.invoke();
		} 
		return timeOut(request, response);
	}
	
	
	private String timeOut(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String path = URLEncoder.encode(getRequestedURL(request), "UTF-8");
		request.setAttribute("redirectURL", "login/index.do?redirectURL=" + path);
		response.setHeader("redirectURL", path);
		response.setHeader("SessionStatus", TIMEOUT);
		return "redirect";
	}
	
	private String getRequestedURL(HttpServletRequest request) {
		StringBuilder param = new StringBuilder();
		Enumeration<String> nameEnum = request.getParameterNames();
		while (nameEnum.hasMoreElements()) {
			String paramName = nameEnum.nextElement();
		    if(param.length() == 0) {
		    	param.append("?");
		    } else {
		    	param.append("&");
		    }
		    param.append(paramName + "=" + request.getParameter(paramName));
		}
		return request.getRequestURL().toString() + param.toString();
	}
}
